#include "Game.h"

#include "protocol/JoinMessage.h"
#include "protocol/JoinResponseMessage.h"

#include "protocol/ServerProtocol.h"

Game Game::singleton;


Game::Game(void)
	: _players(), _nick("server"), _proto(NULL), _serverPort(666), _serverIp("127.0.0.1")
{

}
Game::~Game(void)
{

}

Game& Game::getInstance(void)
{
	return singleton;
}

void Game::initServer(const WindowSettings& ws)
{
	unsigned short port = 666;
	if( ws.hasParameter("--port") )
	{
		port = atoi( ws.getParameter("--port").c_str() );
		std::cout << port << std::endl;
	}

	_proto = new ServerProtocol( port );

	//
	Message *msg;
	do
	{
		msg = _proto->receive();
		delete msg;
		msg = NULL;
	}while( msg == NULL );

	std::cout << "recebido!\n";
}
void Game::initClient( const WindowSettings& ws )
{
	if( ws.hasParameter("--nick") )
		_nick = ws.getParameter("--nick");
	if( _players.find(_nick) != _players.end() )
		return;

	unsigned short port = 667;
	if( ws.hasParameter("--port") )
		port = atoi( ws.getParameter("--port").c_str() );
	if( ws.hasParameter("--server-ip") )
		_serverIp = ws.getParameter("--server-ip");
	if( ws.hasParameter("--server-port") )
		_serverPort = atoi( ws.getParameter("--server-port").c_str() );


	Object& avatar =  Engine::getInstance().addObject(_nick);
	Material* mat =Engine::getInstance().addMaterial("tank.png");
	avatar.setMaterial( mat );

	Cor cor;

	// TODO mandar mensagem para servidor! incluir nick e porta!
	JoinMessage join;

	join.partida = "partida";

	char portt[32] = {0};
	sprintf( &portt[0], "%d", port );
	join.port = &portt[0];
	join.nick = _nick;

	_proto = new Protocol( atoi(join.port.c_str()) );

	_proto->send( join, _serverIp, _serverPort );
	_proto->send( join, _serverIp, _serverPort );

	Message* ret = NULL;
	do
	{
		ret = _proto->receive();
		///std::cout << "recebendo..\n";
	}while( ret == NULL );

	std::cout << "conectado!" << std::endl;

	//_proto->send( join,  );




	Player player( _nick, avatar, cor );

	_players[ _nick ] = player;
}


Protocol* Game::getProtocol(void)
{
	return _proto;
}
